package com.mokylin.dbschema.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;

/**
 * @author 李朝(Li.Zhao)
 * @since 2015/8/31.
 */

public class FileUtils {
    private static final Logger LOG = LoggerFactory.getLogger(FileUtils.class);
    public static String readAll(File file){
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
            StringBuilder content = new StringBuilder();
            String line = null;
            while ((line=reader.readLine())!=null){
                content.append(line+"\n");
            }
            return content.toString();
        } catch (IOException e) {
            LOG.error(e.getMessage(),e);
        }finally {
            closeQuietly(reader);
        }
        return null;
    }

    public static void closeQuietly(Closeable closeable){
        if(closeable!=null ){
            try {
                closeable.close();
            } catch (IOException e) {
                //ignore;
            }
        }
    }


    public static FileOutputStream openOutputStream(File file, boolean append) throws IOException {
        if(file.exists()) {
            if(file.isDirectory()) {
                throw new IOException("File \'" + file + "\' exists but is a directory");
            }

            if(!file.canWrite()) {
                throw new IOException("File \'" + file + "\' cannot be written to");
            }
        } else {
            File parent = file.getParentFile();
            if(parent != null && !parent.mkdirs() && !parent.isDirectory()) {
                throw new IOException("Directory \'" + parent + "\' could not be created");
            }
        }

        return new FileOutputStream(file, append);
    }

    public static long copyInputStreamToFile(InputStream source, File destination) throws IOException {
        try {
            FileOutputStream output = openOutputStream(destination,false);

            try {
                long count = copyLarge(source, (OutputStream) output, (byte[]) (new byte[4096]));
                return count > Integer.MAX_VALUE?-1:(int)count;

            } finally {
                closeQuietly(output);
            }
        } finally {
            closeQuietly(source);
        }

    }

    public static long copyLarge(InputStream input, OutputStream output, byte[] buffer) throws IOException {
        long count = 0L;

        int n1;
        for(boolean n = false; -1 != (n1 = input.read(buffer)); count += (long)n1) {
            output.write(buffer, 0, n1);
        }
        return count;
    }

}
